package com.hcyy.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import com.hcyy.dao.CartDao;
import com.hcyy.dao.CustOrderDao;
import com.hcyy.dao.CustOrderMxDao;
import com.hcyy.dao.ProductDao;
import com.hcyy.dao.UserDao;
import com.hcyy.entity.BaseProperty;
import com.hcyy.entity.Cart;
import com.hcyy.entity.CustOrder;
import com.hcyy.entity.CustOrderLog;
import com.hcyy.entity.CustOrderMx;
import com.hcyy.entity.Product;
import com.hcyy.entity.User;
import com.hcyy.service.CustOrderService;
import com.hcyy.util.SidUtil;
import com.hcyy.util.UserUtil;

@Service
@Transactional
public class CustOrderServiceImpl implements CustOrderService {
	private static Logger logger=LoggerFactory.getLogger(CustOrderServiceImpl.class);
	@Autowired
	private CustOrderDao custOrderDao;
	@Autowired
	private CustOrderMxDao custOrderMxDao;
	@Autowired
	private CartDao cartDao;
	@Autowired
	private ProductDao productDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserUtil userUtil;
	@SuppressWarnings("finally")
	@Override
	public CustOrder addOrder(Map<String,Object> map,Model model,HttpServletRequest request) {
		//获取提交订单中商品所在购物车的cid
		String ids=(String) map.get("idarray");
		if(ids=="")return null;
		String[] idarray=ids.split(",");
		Double totalamount=Double.parseDouble((String) map.get("totalamount"));
		String dwbh= userUtil.findUser(request).getDwbh();
		//留言
		String fnote=(String) map.get("fnote");
		String beizhu1 = (String)map.get("beizhu1");
		//发票类型
		String invoicetype=(String) map.get("invoicetype");
		String fptype="";
			switch (invoicetype) {
			case "1":
				fptype="普";
				break;
			default:
				fptype="专";
				break;
			}
		String thfs=(String) map.get("thfs");//提货方式
		List<CustOrderMx> mxlist=new ArrayList<CustOrderMx>();
		Integer sjid=(Integer) request.getSession().getAttribute("sjid");
		//生成订单号（日期+流水号）
		String lastSid=custOrderDao.findOrderLastSid(dwbh,sjid);
//		String sid=SidConvertor.makeSid(lastSid);
		String sid=SidUtil.createSid(dwbh, lastSid,sjid);
		//根据cid查找所有购物车商品
		List<Cart> cartlist=cartDao.findCartByCidArray(idarray,dwbh,sjid);
		//遍历购物车，存入订单明细表
		int count=0;
		if(cartlist!=null){
			for(Cart cart:cartlist){
				CustOrderMx mx=new CustOrderMx();
				mx.setFAmt(cart.getFAmt());
				mx.setFPrice(cart.getFPrice());
				mx.setFQty(cart.getFQty());
				mx.setPihao(cart.getPihao());
				mx.setSjid(cart.getSjid());
				mx.setSpid(cart.getSpid());
				mx.setSid(sid);
				mx.setZhongbz(cart.getZhongbz());
				mxlist.add(mx);
				custOrderMxDao.insertCustOrderMx(mx);
				//更新购物车表，set isOrder=1；
//				cartDao.updateCart2Order(cart.getCid());
				//删除购物车中已提交订单的商品
				cartDao.deleteCartAfterOrder(cart.getSpid(), dwbh);
				count+=cart.getFQty();
			}
		}
		//存入订单表
		String manager="";//地总
		String fnumber="";//地总的id
		String swzy="";//商务专员
		String managerSz="";//省总
		try {
			User user=userDao.findManagerByDwbh(dwbh,sjid);//每一个用户对应一个地总；
			if(user!=null){
				manager=user.getManager();
				fnumber=user.getFnumber();
				swzy=user.getSwzy();
			}
			if(fnumber!=""){
				managerSz=userDao.findManagerSzByManager(fnumber,sjid);
				if(managerSz==null)managerSz="";
			}
			String shwdjh = (String)map.get("shwdjh");
            if(!"".equals(shwdjh)){
                User us = new User();
                us.setDwbh(dwbh);
                us.setShwdjh(shwdjh);
                userDao.updateUser(us);
            }
		} catch (Exception e) {
			throw e;
		} finally{
			CustOrder order=new CustOrder();
			order.setSid(sid);
			order.setDwbh(dwbh);
			order.setFQty(count);
			order.setFAmount(totalamount);
			order.setFNote(fnote);
			order.setBeizhu1(beizhu1);
			order.setPaykind(5);
			order.setKfp(fptype);
			order.setThfs(thfs);
			order.setManager(manager);
			order.setManagerSz(managerSz);
			order.setSwzy(swzy);
			order.setSjid(sjid);
			custOrderDao.insertOrder(order);
			//存入订单日志表
			CustOrderLog log=new CustOrderLog();
			String fNote="[1]提交订单，配送："+thfs+"，发票："+fptype+"，付款方式：个人账户，留言："+fnote;
			log.setSid(sid);
			log.setFNote(fNote);
			custOrderDao.insertOrderLog(log);
			return order;
		}
	}
	
	//快速下单提交
	@Override
	public CustOrder addQuickOrder(Map<String,Object> map,Model model,HttpServletRequest request) {
		String spids=(String) map.get("spidarray");
		String nums=(String) map.get("numarray");
		String[] spidarray=spids.split(",");
		String[] numarray=nums.split(",");
		Integer sjid=(Integer) request.getSession().getAttribute("sjid");
		List<Product> productlist= new ArrayList<Product>();
		for(int i=0;i<spidarray.length;i++){
			Product product=productDao.findProductById(spidarray[i],sjid);
			product.setNum(Integer.parseInt(numarray[i]));
			productlist.add(product);
		}
		Double totalamount=Double.parseDouble((String) map.get("totalamount"));
		String dwbh= userUtil.findUser(request).getDwbh();
		//留言
		String fnote=(String) map.get("fnote");
		String beizhu1 = (String) map.get("beizhu1");
		//发票类型
		String invoicetype=(String) map.get("invoicetype");
		String fptype="";
		switch (invoicetype) {
		case "1":
			fptype="普";
			break;
		default:
			fptype="专";
			break;
		}
		String thfs=(String) map.get("thfs");//提货方式
		List<CustOrderMx> mxlist=new ArrayList<CustOrderMx>();
		//生成订单号（日期+流水号）
		String lastSid=custOrderDao.findOrderLastSid(dwbh,sjid);
//		String sid=SidConvertor.makeSid(lastSid);
		String sid=SidUtil.createSid(dwbh, lastSid,sjid);
		int count=0;
		if(productlist!=null){
			for(Product product:productlist){
				CustOrderMx mx=new CustOrderMx();
				mx.setFQty(product.getNum());
				double price=judgePrice(mx.getFQty(),product);
				mx.setFPrice(price);
				mx.setPihao(product.getPihao());
				mx.setSjid(sjid);
				mx.setSpid(product.getSpid());
				mx.setSid(sid);
				mx.setZhongbz(product.getZhongbz());
				mxlist.add(mx);
				custOrderMxDao.insertCustOrderMx(mx);
				count+=product.getNum();
				//更新购物车表，set isOrder=1；
//				cartDao.updateQuickCart2Order(product.getSpid(), dwbh);
				cartDao.deleteCartAfterOrder(product.getSpid(), dwbh);
			}
		}
		//存入订单表
		String manager="";
		String fnumber="";
		String swzy="";
		String managerSz="";
		try {
			User user=userDao.findManagerByDwbh(dwbh,sjid);//每一个用户对应一个地总；
			if(user!=null){
				manager=user.getManager();
				fnumber=user.getFnumber();
				swzy=user.getSwzy();
			}
			if(fnumber!=""){
				managerSz=userDao.findManagerSzByManager(fnumber,sjid);
				if(managerSz==null)manager="";
			}
			String shwdjh = (String)map.get("shwdjh");
            if(!"".equals(shwdjh)){
                User us = new User();
                us.setDwbh(dwbh);
                us.setShwdjh(shwdjh);
                userDao.updateUser(us);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		CustOrder order=new CustOrder();
		order.setSid(sid);
		order.setDwbh(dwbh);
		order.setFQty(count);
		order.setFAmount(totalamount);
		order.setFNote(fnote);
		order.setBeizhu1(beizhu1);
		order.setPaykind(5);
		order.setKfp(fptype);
		order.setThfs(thfs);
		order.setManager(manager);
		order.setManagerSz(managerSz);
		order.setSwzy(swzy);
		order.setSjid(sjid);
		custOrderDao.insertOrder(order);
		//存入订单日志表
		CustOrderLog log=new CustOrderLog();
		String fNote="[1]提交订单，配送："+thfs+"，发票："+fptype+"，付款方式：个人账户，留言："+fnote;
		log.setSid(sid);
		log.setFNote(fNote);
		custOrderDao.insertOrderLog(log);
		return order;
	}

	@Override
	public CustOrder findOrderBySid(String sid,String userid) {
		return custOrderDao.findOrderBySid(sid,userid);
	}

	@Override
	public List<CustOrder> findOrderByDwbh(String orderstatus,String dwbh,int sjid) {
		List<CustOrder> orderList=null;
		//判断页面传入的“状态”参数
		if(orderstatus.equals("0")){
			orderList=custOrderDao.findAllOrders(dwbh,sjid);
		}else{
			//num1：表示isPay，num2：表示isDeliver
			byte num1 = 0,num2 = 0;
			switch(orderstatus){
				case "1":
				num1=0;num2=0;	
				break;
				case "2":
				num1=1;num2=0;
				break;
				case "3":
				num1=1;num2=1;
				break;
				default:
				num1=2;num2=2;
			}
			orderList=custOrderDao.findOrderByDwbh(dwbh,sjid, num1, num2);
		}
		return orderList;
	}

	@Override
	public int cancelOrderBySid(String sid, String dwbh) {
		int n= custOrderDao.cancelOrderBySid(sid, dwbh);
		if(n>0){
			CustOrderLog log=new CustOrderLog();
			String fNote="[x]订单取消:客户取消";
			log.setSid(sid);
			log.setFNote(fNote);
			custOrderDao.insertOrderLog(log);
		}
		return n;
	}

	//支付成功
	@Override
	public void paySuccess(String sid) {
		try {
			int rowAffect = 0;
			if(sid.startsWith("T")){
				int i =custOrderDao.updateTpOrder(sid);
			}else{
				Map params = new HashMap();
				params.put("sid", sid);
				params.put("rowAffect", 0);
				custOrderDao.paySuccess(params);
				rowAffect = (int) params.get("rowAffect");
			}
			if(rowAffect>0){
				CustOrderLog log=new CustOrderLog();
				String fNote="B2B微信付款成功";
				log.setSid(sid);
				log.setFNote(fNote);
				custOrderDao.insertOrderLog(log);
			}
		} catch (Exception e) {
			logger.warn("B2B订单回写有问题");
			e.printStackTrace();
		}
	}

	//修改订单
	@Override
	public String modifyOrder(String sid, int FQty, double FAmount, String[] spids, String[] nums,Integer sjid) {
		StringBuilder msg=new StringBuilder();
		List<Product> productList=new ArrayList<Product>();
		for(int i=0;i<spids.length;i++){
			Product product=productDao.findProductById(spids[i],sjid);
			if(product==null){
				msg.append(spids[i]+"没有找到该商品");
			}else{
				if(product.getPihao()==null||product.getPihao().equals("")){
					msg.append(product.getSpmch()+"库存不足!\n");
				}
				productList.add(product);
			}
		}
		if(msg.toString().equals("")){
			int m=custOrderMxDao.deleteMxBySid(sid);//先删除明细
			int n=custOrderDao.updateOrder(sid, FQty, FAmount);//更新表头
			if(m>0&&n>0){//表头更新成功
				for(int i=0;i<productList.size();i++){
					Product product=productList.get(i);
					CustOrderMx mx=new CustOrderMx();
					mx.setFQty(Integer.parseInt(nums[i]));//单个商品数量
					mx.setSid(sid);//订单号
					mx.setSpid(spids[i]);//商品id
					double price=judgePrice(mx.getFQty(), product);
					mx.setFPrice(price);//价格
					String pihao=product.getPihao();
					mx.setPihao(pihao);//批号
					mx.setSjid(product.getSjid());//商家id
					mx.setZhongbz(product.getZhongbz());//中包装量
					int j=custOrderMxDao.insertCustOrderMx(mx);//再逐条插入明细
					if(j==0){
						msg.append(spids[i]+"写入订单失败!");
						throw new RuntimeException();
					}
				}
				CustOrderLog log=new CustOrderLog();
				String fNote="订单修改成功";
				log.setSid(sid);
				log.setFNote(fNote);
				custOrderDao.insertOrderLog(log);
				msg.append(fNote);
			}else{
				throw new RuntimeException();
			}
		}
		return msg.toString();
	}
	
	private double judgePrice(int FQty, BaseProperty bp) {
		int jlgg=bp.getJlgg();//商品件装量
		Double newpriceChl=bp.getPriceChl();//查询商品的最新价格（拆零价）
		Double newpriceZhj=bp.getPriceZhj();//查询商品的最新价格（整件价）
		double newPrice=newpriceZhj;
		if(newpriceChl!=0&&FQty<jlgg){//数量小于件装量，该商品有拆零价
			newPrice=newpriceChl;
		}
		return newPrice;
	}
}
